package net.ib.mtalk.network.task;

import java.util.UUID;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.UUIDMsg;
import net.ib.mntalk.protocol.Session.CreateViewReq;
import net.ib.mntalk.protocol.Session.CreateViewRes;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.database.DatabaseContract.ViewTable;
import net.ib.mtalk.database.helper.ChatDatabaseHelper;
import net.ib.mtalk.database.helper.InboxDatabaseHelper;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.os.Handler;
import android.util.Log;

public class CreateViewTask extends AsyncNetTask {
	
	private CreateViewReq mCreateViewReq;
	private boolean mIsExist;
	private UUID mClientViewUuid;
	
	public CreateViewTask(Context context, Handler handler,
			CreateViewReq createViewReq, UUID clientViewUuid, 
			boolean isExist){
		super(context, handler);
		this.mCreateViewReq = createViewReq;
		this.mClientViewUuid = clientViewUuid;
		this.mIsExist = isExist;
	}
	
	@Override
	protected TcpEnvelope onPreExecute() {
		
		if(!mIsExist){
			InboxDatabaseHelper.createView(mContext, mClientViewUuid, mCreateViewReq);
		}
		
		TcpEnvelope rev = new TcpEnvelope.Builder()
			.setType(TcpEnvelope.REQUEST)
			.setMessage(mCreateViewReq)
			.setMethodId(Session.View.CreateView)
			.build();
		return rev;
	}
	
	@Override
	protected void onPostExecute(int resultCode, Object sentObject,
			Object receivedObject) {
		MTalkLogWriter.d("CreateViewTask.onPostExecute() resultCode : " + resultCode);
		if (receivedObject == null) {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		CreateViewRes createViewRes = (CreateViewRes) resultEnvelope.getMessage();
		
		MTalkLogWriter.d("CreateViewTask ResponseCode : " + createViewRes.getResponseCode());
		
		if(createViewRes.getResponseCode() == Common.SUCCESS){
			// TODO :
			if(createViewRes.getViewUuid() != null){
				Log.i("ATOM", "view UUID str : " + GpbSupport.UuidMsgToString(createViewRes.getViewUuid()));
				InboxDatabaseHelper.updateViewUuid(mContext, mClientViewUuid, createViewRes.getViewUuid());
				ChatDatabaseHelper.updateViewUuid(mContext, mClientViewUuid, createViewRes.getViewUuid());
			}
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_CREATE_VIEW_SUCCESS));
		} else{
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_CREATE_VIEW_FAIL));
		}
	}
}